package crp.core.portal.domain.services;

import com.google.common.collect.Maps;
import com.qwlabs.lang.C2;
import crp.core.course.app.CourseService;
import crp.core.course.domain.models.CourseEntity;
import crp.core.portal.domain.models.PortalSectionConfig;
import crp.core.portal.domain.models.PortalSectionCourseLoadContext;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@ApplicationScoped
public class PortalSectionCourseFixedLoader implements PortalSectionCourseLoader {
    private final CourseService courseService;

    @Inject
    public PortalSectionCourseFixedLoader(CourseService courseService) {
        this.courseService = courseService;
    }

    @Override
    public Map<String, List<CourseEntity>> load(PortalSectionCourseLoadContext context) {
        Set<String> courseIds = context.getSections().stream()
                .map(PortalSectionCourseLoadContext.SectionWithConfig::getConfig)
                .map(PortalSectionConfig::getFixedCourseIds)
                .filter(Objects::nonNull)
                .flatMap(List::stream)
                .collect(Collectors.toSet());
        Map<String, CourseEntity> byIdCourses = C2.map(courseService.searcher().publicByIds(courseIds),
                CourseEntity::getId, Function.identity());
        Map<String, List<CourseEntity>> sectionCourses = Maps.newHashMap();
        context.getSections().forEach(section -> {
            List<CourseEntity> courses = C2.stream(section.getConfig().getFixedCourseIds())
                    .map(byIdCourses::get)
                    .filter(Objects::nonNull)
                    .limit(context.getLimit())
                    .collect(Collectors.toList());
            sectionCourses.put(section.getSectionId(), courses);
        });
        return sectionCourses;
    }
}
